<template>
  <div class="register">
      <div class="title">欢迎注册</div>
      <van-form>
      <van-field 
       v-model="username" lable="用户名" size="large" placeholder="请输入用户名"
       :rules="[{required: true, message:'用户名不能为空！'}]"/>

       <van-field 
       v-model="password" type="password" lable="密码" size="large" name="validator" placeholder="请输入密码"
        :rules="[{required: true, message:'密码不能为空！'},{validator: validatePassword, message:'密码长度至少为6位'}]"/>
       <!--通过validator返回错误提示 -->
       <van-field v-model="password2" type="password" size="large"
       label="重复密码" placeholder="请再次输入密码" :rules="[{required: true, massage:'重复密码不能为空'},
       {validator:validatorPassword2, message:'前后两次密码不一样'}]"/>
      
       <div style="margin-top: 16px;">
        <van-button round block type="primary" @click="onRegister">注册</van-button>
      </div>
      <div class="footer">
          <span class="login" @click="goLogin">直接登录</span>
      </div>
  </van-form>
  </div>
</template>

<script>
import {getCurrentInstance,ref} from 'vue'
import router from '../router/index';
export default{
  setup(){
      const {proxy} = getCurrentInstance()
      const username = ref('');
      const password = ref('');
      const password2 = ref('');
      const validatePassword = (val) => /\d{6}/.test(val);
      //校验函数可以直接返回一段提示错误
      const validatorPassword2 = (val) => {
        console.log(val);
        if(val !== password.value){
          return false;
        }else{
          return true;
        }
      };
      //判断是否规范输入
      const onRegister = () => {
        if(username.value ==='' || password.value ==='' || password2.value ==='' || password.value != password2.value){
          proxy.$toast.fail('请按照规范输入');
          return;
        }
        const data = {
          username:username.value,
          password:password.value,
          password2:password2.value,
        }
        proxy.$axios.post('/register',data).then(res=>{
          console.log(res);
          proxy.$toast.success('注册成功');
          router.push('/login')
        })
      }
      const goLogin = () => {
        router.push('/login')
      }

      return {
       username,
       password,
       password2,
       onRegister,
       goLogin,
       validatePassword,
       validatorPassword2,
      }
  },
}
</script>

<style>
.register{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #eee;
  height: 100%;
}
.title{
  font-size: 1.75rem;
}
.van-form{
  height: 18.75rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.van-cell--large{
  margin: 0.625rem 0;
  border-radius: 8px;
}
.footer{
    color: #ccc;
    text-align: center;
    font-size: 0.875rem;
    padding: 0.625rem;
}
.login{
  color: #aaa;
  font-weight: bold;
}
</style>

 